package com.morehair.config;

import com.morehair.bean.pojo.User;
import com.morehair.bean.vo.admin.BaseRespVo;
import com.morehair.bean.bo.LoginUser;
import com.morehair.service.admin.AuthService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Author  kkw
 * Date  2021/6/7 11:11
 * Version 1.0
 * Description :
 */
@Component
@Aspect
public class OperateLogAop {
    @Autowired
    AuthService authService;
    @Autowired
    LoginUser loginUser;

    @Pointcut("execution(* com.morehair.controller.admin..*(..))")
    public void login() {

    }

    @Around("login()")
    public Object doAfter(ProceedingJoinPoint joinPoint) throws Throwable {

        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        String host = session.getHost();
        String action = joinPoint.getSignature().getName();
//        Object[] args = joinPoint.getArgs();
//        loginUser= (LoginUser) args[0];
//        String username = loginUser.getUsername();
        int status = 1;
        String comment=null;
        String result =null;

        Object proceed = joinPoint.proceed();
        if (proceed instanceof BaseRespVo) {
            BaseRespVo p = (BaseRespVo) proceed;
            int errno = (int) p.getErrno();
            comment=p.getErrmsg();
            if (errno == 0) {
                status = 1;

            } else {
                status = 0;
            }
        }
        if (status == 1) {
            result="成功";
        }else {
            result="失败";
        }
        String username;
        if (subject.getPrincipal() instanceof User) {
            User user = (User) subject.getPrincipal();
            username = user.getUsername();
        }else {
            username= (String) subject.getPrincipal();
        }

        if (username == null) {
            username="匿名者";
        }
        authService.insertLog(username,host,1,action,status,result,comment);
        return proceed;
    }
}
